import React, { useRef, useEffect } from 'react';

const Ball = function (x, y, dx, dy, radius, color) {
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this.radius = radius;
  this.color = color;

  this.draw = function (ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    ctx.fillStyle = this.color;
    ctx.fill();
  };

  this.update = function (ctx, width, height) {
    if (this.x + this.radius > width || this.x - this.radius < 0) {
      this.dx = -this.dx;
    }
    if (this.y + this.radius > height || this.y - this.radius < 0) {
      this.dy = -this.dy;
    }

    this.x += this.dx;
    this.y += this.dy;

    this.draw(ctx);
  };
};

const CanvasAnimation = () => {
  const canvasRef = useRef(null);
  const ballsRef = useRef([]);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const colors = ['#ff595e', '#1982c4', '#6a4c93', '#8ac926', '#ffca3a'];
    for (let i = 0; i < 50; i++) {
      const radius = 10 + Math.random() * 10;
      const x = Math.random() * (canvas.width - radius * 2) + radius;
      const y = Math.random() * (canvas.height - radius * 2) + radius;
      const dx = (Math.random() - 0.5) * 4;
      const dy = (Math.random() - 0.5) * 4;
      const color = colors[Math.floor(Math.random() * colors.length)];
      ballsRef.current.push(new Ball(x, y, dx, dy, radius, color));
    }

    const animate = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ballsRef.current.forEach(ball => ball.update(ctx, canvas.width, canvas.height));
      requestAnimationFrame(animate);
    };

    animate();

    // 响应式 canvas 尺寸
    const handleResize = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return <canvas ref={canvasRef} style={{ display: 'block' }} />;
};

export default CanvasAnimation;
